<template>
	<!-- 图片上传 -->
	<view class="container">
		<zmm-watermark :watermark="watermark" ></zmm-watermark>
		<view @click="open_img" >
			<image v-for="item in img_src" mode="scaleToFill" :src="item" style="width: 300px;height: 300px;" />
		</view>
		
	</view>
	
	
	<!-- 按钮区域 -->
	<view class="container" >
		<view  style="display: flex;">
			<button  @click="upload()" style="border: 2px solid #0099CC;" 
			:disabled="uploadDisabled" :loading="uploadLoading">
			<view v-if="!uploadLoading">
				<uni-icons type="arrow-up" size="25" ></uni-icons>
			</view>
			</button>
			<button  @click="cancel()" style="border: 2px solid #0099CC;">
				<uni-icons type="refresh" size="25"></uni-icons>
			</button>
		</view>
	</view>
	<!-- 展示识别结果 -->
	<view v-if ="showResult" style="text-align: center;" class="container" >
		<uni-section title="识别结果"  type="circle" titleColor="grey">
				<uni-notice-bar color="#2979FF" background-color="#EAF2FF" :text="resultMsg" />
		</uni-section>
	</view>
	<view class="container" style="margin-bottom: 20px;">
		<uni-fab ref="fab" :pattern="pattern"  :content="content" direction="vertical" @trigger="trigger"></uni-fab>
	</view>
	
	
</template>
<script>
	import config from '@/common/config.js'
	import {ping}from '@/common/api.js'
	import {conv2cn} from '@/common/conv.js'
	export default {
		data() {
			return {
				ping_str:"",
				img_src:["/static/home/default.jpg"],
				name:'',
				precise:'',
				showResult:false,
				showUpload:false,
				uploadImg:false,
				uploadDisabled:false,
				uploadLoading:false,
				timeConsu:"",
				resultMsg:"",
				deviceID:"",
				pattern: {
						icon:"pyq",
						buttonColor :"#fff",
						iconColor:"#aaa",
					},
					content: [{
							iconPath: '/static/home/skip.png',
							text: '测试图片',
							active: false
						},
						{
							iconPath: '/static/home/time.png',
							text: '历史记录',
							active: false
						},
					],
					watermark:"default"
			}
		},
		onLoad() {
			uni.getSystemInfo({
				success:  (res)=> {
					console.log(res);
					this.deviceID = res.brand+"-"+res.deviceModel+"-"+res.deviceId
				}
			});
			
			console.log(this.deviceID)
			uni.getStorage({
				key: 'uuid',
				success:  (res) =>{
					this.watermark= res.data
				}
			});
			ping().then(res=>{
				if(res.statusCode == 200){
					uni.showToast({
						title:"服务器连接成功",
						icon:'none',
						duration:1000
					})
				}
			})
		},
		methods: {
			// 悬浮按钮点击事件
			trigger(e) {

				if(e.index == 1){
					uni.navigateTo({
						url:"/pages/my/history"
					})
				}else if(e.index == 0){
					this.img_src = ["/static/home/test.jpg"]
					this.uploadImg = true
					this.showResult = false,
					this.resultMsg=""
					uni.showToast({
						title:"已加载测试图片",
						icon:"success"
					})
				}
			},
			//打开图片
			open_img(){
				uni.chooseImage({
					count:1,
					sourceType:['album','camera'],
					success:res=> {
						// console.log(res.tempFilePaths)
						this.img_src = res.tempFilePaths;
						// console.log(this.img_src)
						this.uploadImg = true
						this.showResult = false,
						this.resultMsg=""
					}
				})
			},
			// 上传图片
	upload() {
		this.uploadDisabled = true;
		this.uploadLoading = true;
		
		if (this.uploadImg) {
			this.resultMsg = "";
			
			const uploadFilePromise = new Promise((resolve, reject) => {
				uni.uploadFile({
					url: "app/analysis",
					filePath: this.img_src[0],
					name: 'file',
					// data:{
					// 	"device":this.deviceID
					// },
					//此处添加device
					header:{'Authorization':uni.getStorageSync('token'),'DeviceID':this.deviceID},
					success: (res) => {
						console.log("识别 res")
						console.log(res)
						res = JSON.parse(res.data);
						res = res.data;
						this.name = conv2cn(res.type);
						
						let precise = res.precise * 100;
						precise = precise.toFixed(2);
						this.precise = precise + "%";
						
						let consume = res.time * 100;
						consume = consume.toFixed(2);
						this.timeConsu = consume;
						
						this.showResult = true;
						let str = `图片识别的结果为有${this.precise}的可能为${this.name} 识别总耗时${this.timeConsu}ms`;
						let index = 0;
						let len = str.length;
						const interval = setInterval(() => {
							if (index < len) {
								this.resultMsg += str[index];
								index++;
							} else {
								clearInterval(interval);
								resolve(); // 上传操作完成后 resolve
							}
						}, 150);
					}
				});
			});
        
        uploadFilePromise.then(() => {
			this.uploadLoading = false;
            this.uploadDisabled = false; // 在上传操作完成后再将 uploadDisabled 设置为 false
        });
    } else {
        uni.showToast({
            title: "请选择图片",
            icon: 'error',
            duration: 1000
        });
        this.uploadDisabled = false // 如果没有选择图片，也需要将 uploadDisabled 设置为 false
		this.uploadLoading = false
    }
}
,
		//取消上传 并清空
		cancel(){
			this.img_src = ["/static/home/default.jpg"]
			this.showResult = false
			this.uploadImg = false
			this.uploadLoading = false
			this.uploadDisabled = false
		},
		
	},
	
	}
</script>

<style>
	.container {
		padding: 20px;
		font-size: 14px;
		line-height: 24px;
	}
	image {
	display: block;
	margin: 0 auto;
	}
</style>
